// pages/train/traindetail/traindetail.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    video_id: '',
    detail: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getDetail(options.id)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  getDetail: function(vid) {
    const that = this
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1s/video/detail?access_token=' + accessToken,
        data: {
          video_id: vid
        },
        success: res => {
          if(res.data.status === 1) {
            that.setData({
              detail: res.data.data
            })
          }
        }
      })
    })
  },

  bought: function() {
    const that = this
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/v1s/order/buy-video?access_token=' + accessToken,
        data: {
          video_id: that.data.detail.id
        },
        success: res => {
          if (res.data.data.is_balance === 1) {
            wx.showModal({
              title: '提示',
              content: '余额抵扣成功',
              showCancel: false,
              success: info => {
                if (info.confirm) {
                  wx.redirectTo({
                    url: '/pages/user/mytrain/mytrain',
                  })
                }
              }
            })
          } else {
            wx.request({
              url: app.globalData.hostAPI + '/v1s/wxpay/unified-order?access_token=' + accessToken,
              data: {
                order_no: res.data.data.order_no
              },
              success: res1 => {
                wx.requestPayment({
                  timeStamp: res1.data.data.timeStamp,
                  nonceStr: res1.data.data.nonceStr,
                  package: res1.data.data.package,
                  signType: 'MD5',
                  paySign: res1.data.data.paySign,
                  success: suc => {
                    wx.showModal({
                      title: '提示',
                      content: '支付成功',
                      showCancel: false,
                      success: info => {
                        if (info.confirm) {
                          wx.redirectTo({
                            url: '/pages/user/mytrain/mytrain',
                          })
                        }
                      }
                    })
                  }
                })
              }
            })
          }
        }
      })
    })
  }
})